package com.imooc.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * redis限流
 *
 * @author 顾志杰
 * @date 2020/9/17-15:00
 */
@Configuration
public class RedisLimiterConfiguration {
    /**
     * HostAddress的Key
     */
    @Bean
    @Primary
    public KeyResolver remoteAddrKeyResolver() {
        return exchange -> Mono.just(
                Objects.requireNonNull(exchange
                        .getRequest()
                        .getRemoteAddress())
                        .getAddress()
                        .getHostAddress()
        );
    }

    @Bean("redisRateLimiterUser")
    @Primary
    public RedisRateLimiter redisRateLimiterUser(){
        return new RedisRateLimiter(1,2);
    }

    @Bean("redisRateLimiterItem")
    public RedisRateLimiter redisRateLimiterItem(){
        return new RedisRateLimiter(20,50);
    }

}
